package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.handler.TurnTableHandler;
import com.ygqh.baby.model.DrawPrize;
import com.ygqh.baby.model.FriendsRankings;
import com.ygqh.baby.model.PrizeItem;
import com.ygqh.baby.model.PrizeItem.Type;
import com.ygqh.baby.po.*;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.HttpUtil;
import com.ygqh.baby.utils.ImageUtils;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/mobile/drawprize")
public class YgDrawPrizeController extends BaseController {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private YgDrawPrizeService ygDrawPrizeService;
	@Autowired
	private YgUserPrizeService ygUserPrizeService;
	@Autowired
	private FileService fileService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private YgDrawPrizeHelpService ygDrawPrizeHelpService;
	@Autowired
	private YgDrawPrizeRecordService ygDrawPrizeRecordService;
	@Autowired
	private YgCardCouponService ygCardCouponService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private TurnTableHandler turnTableHandler;
	@Autowired
	private YgCouponDetailService ygCouponDetailService;
	@Value("${image.domain}")
	private String domain;

	private static final String prizeItemKey = "DRAW_PRIZE_ITEMS";
	private static final String sourceCode = "DRAW_PRIZE_SOURCE";

	@RequestMapping(value = "drawPrize", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject drawPrize(String callback) {
		YgUser user = SessionUtil.getCurrentUser();

		String res = redisDao.get(prizeItemKey);
		if (StringUtils.isBlank(res)) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		DrawPrize drawPrize = JSON.parseObject(res, DrawPrize.class);
		if (!drawPrize.isValid()) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		String baseKey = drawPrize.getBaseKey(false);

		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(user.getId(), baseKey);
		int lastCount = ygDrawPrizeService.findLastCountByUserId(user.getId(), drawPrize.getSourceCode());
		for (PrizeItem item : drawPrize.getPrizeItems()) {
			if (userDrawPrize == null || userDrawPrize.getRate().compareTo(item.getRate()) != 0) {
				continue;
			}
			// 校验奖品是否已兑换
			int userCashCount = ygDrawPrizeRecordService.findCashCountByUserId(user.getId(), baseKey, null, null, true);
			if (userCashCount > 0) {
				return new JSONPObject(callback, Message.error("亲，奖品已兑换成功", -1));
			}

			// 能量是否已集满
			boolean isFull;
			if (item.getDrawCount() != null) {
				// 是否达到总次数要求
				int count = ygDrawPrizeRecordService.countByUserId(user.getId(), item.getType(), baseKey);
				isFull = count >= item.getDrawCount();
			} else {
				// 能量之和是否已满
				BigDecimal totalRate = ygDrawPrizeRecordService.getTotalRateByUserId(user.getId(), item.getType(), baseKey);
				isFull = totalRate != null && totalRate.compareTo(BigDecimal.ONE) >= 0;
			}
			if (isFull) {
				item.setTotalRate(BigDecimal.ONE);
				item.setThisRate(BigDecimal.ZERO);
				item.setLastCount(lastCount);
				return new JSONPObject(callback, Message.success(item));
			}
		}

		if (lastCount <= 0) {
			return new JSONPObject(callback, Message.error("亲，您的次数已用完，赶快去邀请助力吧", -1));
		}

		int cashCount = ygDrawPrizeRecordService.findCashCountByUserId(null, baseKey, null, null, true);
		if (drawPrize.getGiveCount() != null && cashCount >= drawPrize.getGiveCount()) {
			return new JSONPObject(callback, Message.error("亲，您来晚了，赠品已送完", cashCount));
		}

		// drawPrize = InitPrizeItemRule.getRuleList(drawPrize);
		PrizeItem prizeItem = ygDrawPrizeService.drawPrizeByRate(drawPrize, user);
		prizeItem.setLastCount(lastCount - 1);
		return new JSONPObject(callback, Message.success(prizeItem));
	}

	@RequestMapping(value = "drawPrizeV2", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject drawPrizeV2(String callback, Boolean falg) {
		YgUser user = SessionUtil.getCurrentUser();

		String res = redisDao.get(prizeItemKey);
		if (StringUtils.isBlank(res)) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		DrawPrize drawPrize = JSON.parseObject(res, DrawPrize.class);

		String baseKey = drawPrize.getBaseKey(false);

		if (!drawPrize.isValid()) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		//
		int lastCount = ygDrawPrizeService.findLastCountByUserId(user.getId(), drawPrize.getSourceCode());
		if (lastCount <= 0) {
			return new JSONPObject(callback, Message.success("亲，您的次数已用完，赶快去邀请助力吧", -1));
		}
		int cashCount = ygDrawPrizeRecordService.findCashCountByUserId(null, baseKey, null, null, true);
		if (cashCount >= drawPrize.getGiveCount()) {
			return new JSONPObject(callback, Message.success("亲，您来晚了，赠品已送完", cashCount));
		}

		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(user.getId(), baseKey);
		if (userDrawPrize.getRate().compareTo(new BigDecimal("0.00")) > 0) {

			int userCashCount = ygDrawPrizeRecordService.findCashCountByUserId(user.getId(), baseKey, null, null, true);
			if (userCashCount > 0) {
				falg = false;
			}
		}
		drawPrize.setFalg(falg);

		PrizeItem prizeItem = ygDrawPrizeService.drawPrizeByRate(drawPrize, user);

		prizeItem.setLastCount(lastCount - 1);
		return new JSONPObject(callback, Message.success(prizeItem));
	}

	@RequestMapping("getCodeUrl")
	@ResponseBody
	public JSONPObject getCodeUrl(String callback) {
		YgUser currentUser = SessionUtil.getCurrentUser();
		String result = redisDao.get("getCodeUrl-" + currentUser.getId());
		if (StringUtils.isNotBlank(result)) {
			return new JSONPObject(callback, Message.error("操作频繁，稍后重试", null));
		}
		redisDao.set("getCodeUrl-" + currentUser.getId(), "1", 5 * 1000);
		Message message = validateDrawPrize();
		if (!Message.isSuccess(message)) {
			redisDao.del(("getCodeUrl-" + currentUser.getId()).getBytes());
			return new JSONPObject(callback, message);
		}
		DrawPrize drawPrize = (DrawPrize) message.getExtra();
		String baseKey = drawPrize.getBaseKey(false, Constant.YIIGOO_PLATFORM_NO);
		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(currentUser.getId(), baseKey);
		if (userDrawPrize == null) {
			userDrawPrize = ygDrawPrizeService.initDrawPrize(baseKey, currentUser.getId(), 0, 1);
		} else if (StringUtils.isNotBlank(userDrawPrize.getQrCode())) {
			return new JSONPObject(callback, Message.success(userDrawPrize.getQrCode()));
		}
		String codeUrl;
		try {
			codeUrl = wxMpAuthorityService.findQrCodeUrl("DrawPrize-" + baseKey + "-" + currentUser.getUserName());
		} catch (WeixinException e) {
			logger.error("【转盘抽奖】公众号二维码生成失败，" + e.getMessage(), e);
			redisDao.del(("getCodeUrl-" + currentUser.getId()).getBytes());
			return new JSONPObject(callback, Message.error("生成二维码异常，请稍后再试或联系客服", null));
		}
		YgDrawPrize record = new YgDrawPrize();
		record.setId(userDrawPrize.getId());
		record.setQrCode(codeUrl);
		ygDrawPrizeService.update(record);
		redisDao.del(("getCodeUrl-" + currentUser.getId()).getBytes());
		return new JSONPObject(callback, Message.success(codeUrl));
	}

	@RequestMapping("getCodeUrlByFromCode")
	@ResponseBody
	public JSONPObject getCodeUrl(String callback, @RequestParam String fromCode) {
		Message message = validateDrawPrize();
		if (!Message.isSuccess(message)) {
			return new JSONPObject(callback, message);
		}
		DrawPrize drawPrize = (DrawPrize) message.getExtra();
		String baseKey = drawPrize.getBaseKey(false, Constant.YIIGOO_PLATFORM_NO);
		YgUser fromUser = ygUserService.findBySourceCode(fromCode);
		if (fromUser == null) {
			logger.error("【转盘抽奖】邀请助力链接source异常，fromCode={}", fromCode);
			return new JSONPObject(callback, Message.error("系统异常，请请稍后再试或联系客服", null));
		}
		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(fromUser.getId(), baseKey);
		if (userDrawPrize == null) {
			logger.error("【转盘抽奖】邀请助力链接source异常，fromCode={}", fromCode);
			return new JSONPObject(callback, Message.error("系统异常，请请稍后再试或联系客服", null));
		}
		if (StringUtils.isNotBlank(userDrawPrize.getQrCode())) {
			return new JSONPObject(callback, Message.success(userDrawPrize.getQrCode()));
		}
		String codeUrl;
		try {
			codeUrl = wxMpAuthorityService.findQrCodeUrl("DrawPrize-" + baseKey + "-" + fromCode);
		} catch (WeixinException e) {
			logger.error("【转盘抽奖】公众号二维码生成失败，" + e.getMessage(), e);
			return new JSONPObject(callback, Message.error("生成二维码异常，请稍后再试或联系客服", null));
		}
		YgDrawPrize record = new YgDrawPrize();
		record.setId(userDrawPrize.getId());
		record.setQrCode(codeUrl);
		ygDrawPrizeService.update(record);
		return new JSONPObject(callback, Message.success(codeUrl));
	}

	private String saveImageToTarget(HttpServletRequest request, String codeUrl, String key, String source) throws Exception {
		String ext = ".jpg";
		String path = request.getRealPath("/");
		String targetPath = path + "/niuyiniu";
		String ditu = HttpUtil.saveImageToTargetDisk(domain + "default/zhuawawa.jpg", targetPath + "/" + source + "_ditu" + ext);
		String shareCodeUrl = HttpUtil.saveImageToTargetDisk(codeUrl, targetPath + "/" + key + ext);

		ImageUtils.pressImageMark2(shareCodeUrl, ditu, shareCodeUrl, 100, 780, 1.0f, 180, 180);

		File file = new File(shareCodeUrl);

		shareCodeUrl = fileService.uploadImage(file, new FileType[]{FileType.QrCode}, ext, true, request);
		return shareCodeUrl;

	}

	;

	@RequestMapping(value = "/getPrizeCards")
	@ResponseBody
	public JSONPObject getPrizeCards(String callback) {
		List<YgCardCoupon> list = ygCardCouponService.findCardsByMonth(CardType.DrawPrize, CardMode.Goods, null);
		return new JSONPObject(callback, Message.success(list));
	}

	@RequestMapping(value = "/generateCard")
	@ResponseBody
	public JSONPObject generateCard(Long cardId, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String source = redisDao.get(sourceCode);
		Message message = ygUserPrizeService.generateCardCoupon(user.getId(), cardId, source);
		return new JSONPObject(callback, message);
	}

	@RequestMapping(value = "/findMyPrize")
	@ResponseBody
	public JSONPObject findMyPrize(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		ygUserPrizeService.findPrizeItemByUserId(user.getId(), Type.Goods, "");
		return new JSONPObject(callback, Message.success(null));
	}

	@RequestMapping(value = "/findMyGoodsPrize")
	@ResponseBody
	public JSONPObject getPrize(QueryInfo queryInfo, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String source = redisDao.get(sourceCode);
		YgUserPrize prize = ygDrawPrizeRecordService.findMyGoodsPrize(user.getId(), source);
		if (prize == null) {
			prize = new YgUserPrize();
			prize.setUserId(user.getId());
		}
		int cashCount = ygDrawPrizeRecordService.findCashCountByUserId(user.getId(), source, null, null, true);
		prize.setExchangeCount(cashCount);
		Map<String, Object> map = new HashMap<String, Object>();
		queryInfo = new QueryInfo(0, 30);
		List<YgDrawPrizeHelp> list = ygDrawPrizeHelpService.getWxHelpList(queryInfo, user.getId(), source);
		map.put("prize", prize);
		map.put("helpList", list);
		return new JSONPObject(callback, Message.success(map));
	}

	@RequestMapping(value = "/cashPrize")
	@ResponseBody
	public JSONPObject cashCard(Long priziId, String addrInfo, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		YgUserAddress address = JSON.parseObject(addrInfo, new TypeReference<YgUserAddress>() {
		});

		Message message = ygUserPrizeService.cashPrize(priziId, new BigDecimal("1"), user, address);
		return new JSONPObject(callback, message);
	}

	@RequestMapping(value = "/getWxHelpList")
	@ResponseBody
	public JSONPObject getWxHelpList(QueryInfo queryInfo, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String source = redisDao.get(sourceCode);
		List<YgDrawPrizeHelp> list = ygDrawPrizeHelpService.getWxHelpList(queryInfo, user.getId(), source);

		return new JSONPObject(callback, Message.success(list));
	}

	@RequestMapping(value = "/getDrawPrizeCount")
	@ResponseBody
	public JSONPObject getDrawPrizeCount(Long userId, String callback) {
		String source = redisDao.get(sourceCode);
		int count = ygDrawPrizeService.findLastCountByUserId(userId, source);
		return new JSONPObject(callback, Message.success(count));
	}

	@RequestMapping(value = "/getFriendsRankings")
	@ResponseBody
	public JSONPObject getFriendsRankings(String callback) {
		String source = redisDao.get(sourceCode);
		YgUser user = SessionUtil.getCurrentUser();
		List<FriendsRankings> list = ygDrawPrizeService.getFriendsRankings(user.getId(), user.getOpenId(), source);
		return new JSONPObject(callback, Message.success(list));
	}

	@RequestMapping(value = "drawPrizeV3", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject drawPrizeV3(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		Long userId = user.getId();
		String result = redisDao.get("drawPrizeV3-" + userId);
		if (StringUtils.isNotBlank(result)) {
			return new JSONPObject(callback, Message.error("操作频繁，稍后重试", null));
		}
		redisDao.set("drawPrizeV3-" + userId, "1", 5 * 1000);
		Message message = validateDrawPrize();
		if (!message.getType().equals(Message.Type.success)) {
			redisDao.del(("drawPrizeV3-" + userId).getBytes());
			return new JSONPObject(callback, message);
		}
		DrawPrize drawPrize = (DrawPrize) message.getExtra();
		String baseKey = drawPrize.getBaseKey(false, Constant.YIIGOO_PLATFORM_NO);
		// 验证本次活动赠品数量
		int cashCount = ygDrawPrizeRecordService.findCashCountByUserId(null, baseKey, null, null, false);
		if (drawPrize.getGiveCount() != null && cashCount >= drawPrize.getGiveCount()) {
			return new JSONPObject(callback, Message.error("亲，您来晚了，赠品已送完", null));
		}
		// 用户抽奖信息
		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(userId, baseKey);
		boolean isUseDrawCount = false; // 是否使用用户抽奖信息内的抽奖数
		if (userDrawPrize == null) { // 当前用户未参与过抽奖
			userDrawPrize = ygDrawPrizeService.initDrawPrize(baseKey, userId, 0, 1);
		} else {
			Date date = new Date();
			// 查看当天抽奖记录
			int countByCurrentDate = ygDrawPrizeRecordService.findCashCountByUserId(userId, baseKey, DateConvertUtils.getDateStart(date),
					DateConvertUtils.getDateEnd(date), false);
			if (countByCurrentDate > 0) { // 当天有过抽奖记录
				isUseDrawCount = true;
				if (userDrawPrize.getCount() <= 0) { // 用户的剩余抽奖次数已用完
					redisDao.del(("drawPrizeV3-" + userId).getBytes());
					return new JSONPObject(callback, Message.error("亲，您的次数已用完，赶快去邀请助力吧", null));
				}
			}
		}
		PrizeItem prizeItem = ygDrawPrizeService.drawPrizeV3(drawPrize, user, Constant.YIIGOO_PLATFORM_NO);
		if (prizeItem == null) {
			redisDao.del(("drawPrizeV3-" + userId).getBytes());
			return new JSONPObject(callback, Message.error("系统异常，请稍后重试或联系客服", null));
		}
		if (isUseDrawCount) {
			userDrawPrize.setCount(userDrawPrize.getCount() - 1);
			ygDrawPrizeService.updateCountById(userDrawPrize.getCount(), userDrawPrize.getId());
		}
		Map<String, Object> data = new HashMap<>(4);
		data.put("index", prizeItem.getIndex());
		data.put("relationCode", prizeItem.getRelationCode());
		data.put("content", prizeItem.getContent());
		data.put("lastCount", userDrawPrize.getCount());
		data.put("type", prizeItem.getType());
		redisDao.del(("drawPrizeV3-" + userId).getBytes());
		return new JSONPObject(callback, Message.success(data));
	}

	@RequestMapping(value = "/getDrawPrizeCountV3")
	@ResponseBody
	public JSONPObject getDrawPrizeCountV3(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String result = redisDao.get("getDrawPrizeCountV3-" + user.getId());
		if (StringUtils.isNotBlank(result)) {
			return new JSONPObject(callback, Message.error("操作频繁，稍后重试", null));
		}
		redisDao.set("getDrawPrizeCountV3-" + user.getId(), "1", 5 * 1000);
		Message message = validateDrawPrize();
		if (!Message.isSuccess(message)) {
			redisDao.del(("getDrawPrizeCountV3-" + user.getId()).getBytes());
			return new JSONPObject(callback, message);
		}
		DrawPrize drawPrize = (DrawPrize) message.getExtra();
		String baseKey = drawPrize.getBaseKey(false, Constant.YIIGOO_PLATFORM_NO);
		Long userId = user.getId();
		// 用户抽奖信息
		int currentDateCount = 1;
		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(userId, baseKey);
		if (userDrawPrize == null) { // 当前用户未参与过抽奖
			userDrawPrize = ygDrawPrizeService.initDrawPrize(baseKey, userId, 0, 1);
		} else {
			Date date = new Date();
			// 查看当天抽奖记录
			int countByCurrentDate = ygDrawPrizeRecordService.findCashCountByUserId(userId, baseKey, DateConvertUtils.getDateStart(date),
					DateConvertUtils.getDateEnd(date), false);
			if (countByCurrentDate > 0) { // 当天有过抽奖记录
				currentDateCount--;
			}
		}
		redisDao.del(("getDrawPrizeCountV3-" + user.getId()).getBytes());
		return new JSONPObject(callback, Message.success(userDrawPrize.getCount() + currentDateCount));
	}

	/**
	 * 兑换实物奖品
	 *
	 * @param skuId skuId
	 * @param addrInfo 收货地址信息
	 * @return
	 */
	@RequestMapping(value = "/cashGoodsPrizeV3")
	@ResponseBody
	public JSONPObject cashGoodsPrizeV3(@RequestParam Long skuId, @RequestParam String addrInfo,
										   @RequestParam(defaultValue = "WeChat") AppType appType, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String result = redisDao.get("cashGoodsPrizeV3-" + user.getId());
		if (StringUtils.isNotBlank(result)) {
			return new JSONPObject(callback, Message.error("操作频繁，稍后重试", null));
		}
		redisDao.set("cashGoodsPrizeV3-" + user.getId(), "1", 5 * 1000);
		Message message = validateDrawPrize();
		if (!Message.isSuccess(message)) {
			redisDao.del(("cashGoodsPrizeV3-" + user.getId()).getBytes());
			return new JSONPObject(callback, message);
		}
		DrawPrize drawPrize = (DrawPrize) message.getExtra();
		String baseKey = drawPrize.getBaseKey(false, Constant.YIIGOO_PLATFORM_NO);
		YgUserAddress address = JSON.parseObject(addrInfo, new TypeReference<YgUserAddress>() {
		});
		if (address == null) {
			logger.error("【转盘抽奖】前端传递的地址信息异常，addrInfo={}", addrInfo);
			redisDao.del(("cashGoodsPrizeV3-" + user.getId()).getBytes());
			return new JSONPObject(callback, Message.error("地址信息异常，请稍后再试或联系客服", null));
		}
		address.setUserId(user.getId());
		Message message2 = ygUserPrizeService.cashPrize(skuId, baseKey, address, Constant.YIIGOO_PLATFORM_NO, appType);
		redisDao.del(("cashGoodsPrizeV3-" + user.getId()).getBytes());
		return new JSONPObject(callback, message2);
	}

	private Message validateDrawPrize() {
		String res = redisDao.get(RedisConstant.PRIZE_ITEM_KEY);
		if (StringUtils.isBlank(res)) {
			return Message.error("活动已结束", null);
		}
		// 解析抽奖活动信息
		DrawPrize drawPrize = JSON.parseObject(res, DrawPrize.class);
		if (!drawPrize.isValid()) {
			return Message.error("活动已结束", null);
		}
		return Message.success(drawPrize);
	}

	/**
	 * 能量值满，兑换奖品
	 *
	 * @param callback
	 * @return
	 */
	@RequestMapping("cashPrizeByEnergy")
	@ResponseBody
	public JSONPObject cashPrizeByEnergy(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String res = redisDao.get(prizeItemKey);
		if (StringUtils.isBlank(res)) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		DrawPrize drawPrize = JSON.parseObject(res, DrawPrize.class);
		if (!drawPrize.isValid()) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		String baseKey = drawPrize.getBaseKey(false);
		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(user.getId(), baseKey);
		PrizeItem prizeItem = null;
		for (PrizeItem item : drawPrize.getPrizeItems()) {
			if (userDrawPrize.getRate().compareTo(item.getRate()) == 0) {
				prizeItem = item;
				break;
			}
		}

		// 能量是否已集满
		boolean isFull;
		if (prizeItem == null) {
			isFull = false;
		} else if (prizeItem.getDrawCount() != null) {
			// 是否达到总次数要求
			int count = ygDrawPrizeRecordService.countByUserId(user.getId(), prizeItem.getType(), baseKey);
			isFull = count >= prizeItem.getDrawCount();
		} else {
			// 能量之和是否已满
			BigDecimal totalRate = ygDrawPrizeRecordService.getTotalRateByUserId(user.getId(), prizeItem.getType(), baseKey);
			isFull = totalRate != null && totalRate.compareTo(BigDecimal.ONE) >= 0;
		}
		if (!isFull) {
			return new JSONPObject(callback, Message.error("亲，您的能量未集满，赶快去邀请助力吧", -1));
		}
		int userCashCount = ygDrawPrizeRecordService.findCashCountByUserId(user.getId(), baseKey, null, null, true);
		if (userCashCount > 0) {
			return new JSONPObject(callback, Message.error("亲，奖品已兑换成功", -1));
		}
		Object[][] prizeArr = initPrizeForCash();
		Object[] prize = turnTableHandler.turnTable(prizeArr, 0, baseKey, user, drawPrize.getEndDate());
		YgDrawPrizeRecord ygDrawPrizeRecord = new YgDrawPrizeRecord(user.getId(), drawPrize.getSourceCode(), Type.valueOf(prize[4].toString()), prize[1].toString(),
				new BigDecimal("-1"), prize[2].toString(), "", new Date());
		ygDrawPrizeRecordService.save(ygDrawPrizeRecord);
		return new JSONPObject(callback, Message.success(prize[0]));
	}

	/**
	 * 奖品设置；
	 * 设置规则：{奖品索引, 奖品关联参数, 奖品名称, 奖品类型, 限制总数, 限制每日数}
	 *
	 * @return
	 */
	private Object[][] initPrizeForCash() {
		// 测试
		/*return new Object[][]{
				{1, 74, "小短手恐龙玩偶", "20", Type.Goods, 20, null},
				{2, 75, "蓝水玉球球毛巾", "79", Type.Goods, null, null},
				{3, 364, "300元无门槛券", "1", Type.Goods, 1, null}
		};*/
		// 线上
		return new Object[][]{
				{1, 80, "小短手恐龙玩偶", "20", Type.Goods, 20, null},
				{2, 81, "蓝水玉球球毛巾", "79", Type.Goods, null, null},
				{3, 377, "300元无门槛券", "1", Type.Goods, 1, null}
		};
	}

	/**
	 * 助力
	 *
	 * @param callback
	 * @param sourceCode
	 * @return
	 */
	@RequestMapping("addHelp")
	@ResponseBody
	public JSONPObject addHelp(String callback, @RequestParam String sourceCode) {
		String res = redisDao.get(prizeItemKey);
		if (StringUtils.isBlank(res)) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		DrawPrize drawPrize = JSON.parseObject(res, DrawPrize.class);
		if (!drawPrize.isValid()) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		String baseKey = drawPrize.getBaseKey(false);
		YgUser currentUser = SessionUtil.getCurrentUser();
		Boolean hasHelp = ygDrawPrizeHelpService.hasHelpByOpenId(currentUser.getUserName(), baseKey, DataStatus.Valid);
		if (hasHelp) {
			return new JSONPObject(callback, Message.error("您已参与过助力", null));
		}
		YgUser sourceUser = ygUserService.findBySourceCode(sourceCode);
		if (sourceUser == null) {
			return new JSONPObject(callback, Message.error("不存在该用户", null));
		}
		if (!currentUser.getFromCode().equals(sourceUser.getSourceCode())) {
			return new JSONPObject(callback, Message.error("不是注册邀请人source", sourceCode));
		}
		if (currentUser.getCreateTime().before(drawPrize.getStartDate())) {
			return new JSONPObject(callback, Message.error("您不是新注册用户，无法参与助力", sourceCode));
		}
		YgDrawPrizeHelp drawPrizeHelp = new YgDrawPrizeHelp(baseKey, currentUser.getUserName(), currentUser.getNickName(),
				currentUser.getHeadImageUrl(), sourceUser.getId(), 1, new Date());
		ygDrawPrizeHelpService.save(drawPrizeHelp);

		int userCashCount = ygDrawPrizeRecordService.findCashCountByUserId(sourceUser.getId(), baseKey, null, null, true);
		if (userCashCount == 0) {
			// 用户未兑换奖品
			ygDrawPrizeService.addCountByHelp(1, baseKey, sourceUser.getId(), currentUser.getUserName());
		}

		return new JSONPObject(callback, Message.success(null));
	}

	/**
	 * 获取当前用户的初始化信息
	 *
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getDrawPrizeInfo")
	@ResponseBody
	public JSONPObject getDrawPrizeInfo(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String res = redisDao.get(prizeItemKey);
		if (StringUtils.isBlank(res)) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		DrawPrize drawPrize = JSON.parseObject(res, DrawPrize.class);
		if (!drawPrize.isValid()) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		String baseKey = drawPrize.getBaseKey(false);

		Map<String, Object> data = new HashMap<>();
		/*int count = ygDrawPrizeService.findLastCountByUserId(user.getId(), baseKey);
		data.put("count", count);

		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(user.getId(), baseKey);
		PrizeItem prizeItem = null;
		for (PrizeItem item : drawPrize.getPrizeItems()) {
			if (userDrawPrize.getRate().compareTo(item.getRate()) == 0) {
				prizeItem = item;
				break;
			}
		}
		BigDecimal totalRate;
		int totalCount;
		if (prizeItem != null) {
			data.put("drawCount", prizeItem.getDrawCount());
			totalCount = ygDrawPrizeRecordService.countByUserId(user.getId(), prizeItem.getType(), baseKey);
			// 能量是否已集满
			boolean isFull = false;
			if (prizeItem.getDrawCount() != null) {
				// 是否达到总次数要求
				isFull = totalCount >= prizeItem.getDrawCount();
			}
			if (!isFull) {
				totalRate = ygDrawPrizeRecordService.getTotalRateByUserId(user.getId(), prizeItem.getType(), baseKey);
			} else {
				totalRate = BigDecimal.ONE;
			}
		} else {
			totalRate = BigDecimal.ZERO;
			totalCount = 0;
		}
		data.put("totalRate", totalRate);*/
		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(user.getId(), baseKey);
		if (userDrawPrize == null) {
			userDrawPrize = ygDrawPrizeService.initDrawPrize(baseKey, user.getId(), 0, 1);
		}
		data.put("totalCount", userDrawPrize.getCount());
		return new JSONPObject(callback, Message.success(data));
	}

	/**
	 * 气球券活动兑奖（固定奖项）
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/receiveCouponPrize")
	@ResponseBody
	public JSONPObject receiveCouponPrize(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String res = redisDao.get(prizeItemKey);
		if (StringUtils.isBlank(res)) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		DrawPrize drawPrize = JSON.parseObject(res, DrawPrize.class);
		if (!drawPrize.isValid()) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		String baseKey = drawPrize.getBaseKey(false);
		YgDrawPrize userDrawPrize = ygDrawPrizeService.findByUserId(user.getId(), baseKey);
		if (userDrawPrize == null) {
			return new JSONPObject(callback, Message.error("数据异常，请刷新活动页面", null));
		}
		int userCashCount = ygDrawPrizeRecordService.findCashCountByUserId(user.getId(), baseKey, null, null, true);
		if (userCashCount > 0) {
			return new JSONPObject(callback, Message.error("亲，您已领取过优惠券", -1));
		}
		Integer count = userDrawPrize.getCount();
		LinkedList<PrizeItem> prizeItems = drawPrize.getPrizeItems();
		if (count > prizeItems.size() -1) {
			count = prizeItems.size() - 1;
		}
		PrizeItem prizeItem = prizeItems.get(count);
		Message message = ygCouponDetailService.receiveCouponWithRemark(Long.valueOf(prizeItem.getRelationCode()), baseKey, user);
		if (Message.isSuccess(message)) {
			YgDrawPrizeRecord record = new YgDrawPrizeRecord(user.getId(), baseKey, prizeItem.getType(), prizeItem.getRelationCode(),
					new BigDecimal("-1"),  prizeItem.getContent(), "领取成功", new Date());
			ygDrawPrizeRecordService.save(record);
			message.setExtra(userDrawPrize.getCount());
		}
		return new JSONPObject(callback, message);
	}

}
